/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.services.saving;

/**
 *
 * @author jay
 */

import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import src.HibernateUtil;
import src.domain.saving.Savwd;
import src.services.CRUEDService;

public class SavwdModel implements java.io.Serializable {
    
    private CRUEDService service;
    
    public SavwdModel() {
        service = new CRUEDService();
    }
    
    public List<Savwd> findAll(Map<String, Object> filters, String orderby) {
        return (List<Savwd>) service.findAllSQLAdvance(
                "from Savwd", filters, orderby);
    }
    
    public Integer authorized(Integer id) {
         return (Integer) service.getObjectSQL(
                 "select approvalUid from Savwd where savwdId = "+id, null);
    }
    
    public boolean saveData(Savwd data) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        org.hibernate.Transaction tx = session.beginTransaction();
        boolean success;
        
        try {
            session.saveOrUpdate(data);
            
            if (data.getPosted()) {
                session.flush();
                Query q = session.createSQLQuery(" { call saving_modul.savwd_actions (?, ?) }");
                q.setInteger(0,data.getSavwdId());  
                q.setInteger(1,103);  
                q.executeUpdate();
            }
            tx.commit();
            success = true;  
            
        } catch (RuntimeException e) {
            
            if (tx != null && tx.isActive()) {
                try {
                    tx.rollback();
                } catch (HibernateException e1) {}
            }
            success = false;  
            Logger.getLogger(SavwdModel.class.getName()).log(Level.SEVERE, null, e);
        }
        
        return success;
    }
    
    public boolean deleteData(Savwd data) {
        return service.deleteData(data);
    }
}
